package com.moon.icoresso.strategy.impl;

import com.moon.icoresso.Exception.OauthException;
import com.moon.icoresso.Service.OauthRedisService;
import com.moon.icoresso.Service.OauthService;
import com.moon.icoresso.common.utils.StringRedisService;
import com.moon.icoresso.common.utils.StringUtil;
import com.moon.icoresso.pojo.bo.OauthRefreshTokenToRedisBO;
import com.moon.icoresso.pojo.bo.OauthTokenHandleBO;
import com.moon.icoresso.pojo.dto.OauthTokenDTO;
import com.moon.icoresso.pojo.dto.OauthTokenParam;
import com.moon.icoresso.pojo.dto.OauthUserInfo;
import com.moon.icoresso.strategy.OauthStrategy;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import static com.moon.icoresso.pojo.constants.Constants4Oauth.OAUTH_REFRESH_GRANT_TYPE;

/**
 * @ClassName OauthRefreshTokenStrategy
 * @Description
 * @Author menbbo
 * @Date 2021/2/19 21:26
 * @Version V1.0
 **/
@Component(value = OAUTH_REFRESH_GRANT_TYPE)
public class OauthRefreshTokenStrategy implements OauthStrategy {
    @Autowired
    private OauthService oauthService;
    @Autowired
    private StringRedisService<String,OauthRefreshTokenToRedisBO> oauthTokenRedisService;
    @Autowired
    private StringRedisService<String,OauthUserInfo> oauthUserInfoStringRedisService;
    @Autowired
    private OauthRedisService oauthRedisService;
    @Override
    public void checkParam(OauthTokenParam oauthTokenParam, OauthTokenHandleBO oauthTokenHandleBO) {
        oauthService.checkRefreshToken(oauthTokenParam);
        OauthRefreshTokenToRedisBO oauthRefreshTokenToRedisBO = oauthTokenRedisService.get(oauthTokenParam.getRefreshToken());
        if(oauthRefreshTokenToRedisBO==null&& StringUtils.isEmpty(oauthRefreshTokenToRedisBO.getUserInfoToRedisKey())){
            throw new OauthException("refreshToken失效");
        }
        OauthUserInfo oauthUserInfo = oauthUserInfoStringRedisService.get(oauthRefreshTokenToRedisBO.getUserInfoToRedisKey());
        oauthTokenHandleBO.setOauthUserInfo(oauthUserInfo);
    }

    @Override
    public OauthTokenDTO handle(OauthTokenParam oauthTokenParam, OauthTokenHandleBO oauthTokenHandleBO) {
        //获取用户信息保存

        OauthTokenDTO oauthTokenDTO = oauthService.generateToken(false);
        //将token保存
        oauthRedisService.saveAccessToken(oauthTokenParam.getGrantType(),oauthTokenParam.getClientId(),oauthTokenDTO.getAccessToken(),oauthTokenHandleBO.getOauthUserInfo());

        return oauthTokenDTO;
    }
}